package com.can.core.advice;

import com.can.common.constant.JsonResultEnum;
import com.can.entityDTO.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description 请求参数验证捕获控制类
 * @Author can
 * @Date 2018/8/28
 * @Version 1.0
 */
@ControllerAdvice
public class ValidateControllerAdvice {
    private final static Logger logger = LoggerFactory.getLogger(ValidateControllerAdvice.class);
    /**
     * bean校验未通过异常
     *
     * @see javax.validation.Valid
     * @see org.springframework.validation.Validator
     * @see org.springframework.validation.DataBinder
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonResult validExceptionHandler(BindException ex, WebRequest request, HttpServletResponse response) {
        JsonResult jsonResult = new JsonResult(JsonResultEnum.VALIDATE_PARAM_ERROR, ex.getFieldError().getDefaultMessage());
        return jsonResult;
    }

    /**
     * bean校验未通过异常
     *
     * @see javax.validation.Valid
     * @see org.springframework.validation.Validator
     * @see org.springframework.validation.DataBinder
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public JsonResult validExceptionHandler(MethodArgumentNotValidException ex, WebRequest request, HttpServletResponse response) {
        JsonResult jsonResult = new JsonResult(JsonResultEnum.VALIDATE_PARAM_ERROR, ex.getBindingResult().getFieldError().getDefaultMessage());
        return jsonResult;
    }
}
